package com.atguigu.guli.service.oss.controller.admin;

import com.atguigu.guli.service.base.exception.GuliException;
import com.atguigu.guli.service.base.result.R;
import com.atguigu.guli.service.base.result.ResultCodeEnum;
import com.atguigu.guli.service.oss.service.FileService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
@Slf4j
@Api(tags = "阿里云文件管理")
@RestController
@RequestMapping("/aliyun/oss")
@CrossOrigin
public class FileController {
    @Autowired
    FileService fileService;
    @ApiOperation("文件上传")
    @PostMapping("/upload")
    public R upload(@RequestParam MultipartFile file, @RequestParam String model) throws IOException {
        try {
            InputStream inputStream = file.getInputStream();
            String originalFilename = file.getOriginalFilename();
            String upload = fileService.upload(inputStream, model, originalFilename);
            return R.ok().message("文件上传成功").data("url",upload);
        } catch (IOException e) {
            log.error(ExceptionUtils.getStackTrace(e));
            throw new GuliException(ResultCodeEnum.FILE_UPLOAD_ERROR);
        }
    }
    @ApiOperation(value = "测试")
    @RequestMapping("/test")
    public R test(){
        return R.ok().data("message","成功");
    }

    @ApiOperation(value = "删除头像")
    @DeleteMapping("/delete")
    public R deleteFile(@ApiParam(value = "要删除的文件路径", required = true)
                            @RequestBody String url ){
        fileService.removeFile(url);
        return R.ok().message("文件刪除成功");
    }
}
